/*
/*
描述：扫描枪和扫描仪的通用程序
作者：朱振展
联系：442446835@qq.com
日期：2017.04.1
*/


#include <linux/input.h>
#include <sys/time.h>
#include "head.h"
#include "scanner.h"
/*将键值转换成ASCII*/

/*定义一个input_event包获取输入*/

void *scanner(void *args)
{
	
	char Keyboard_ascii[100] = {
		[11] = '0', [ 2] = '1', [ 3] = '2', [ 4] = '3', [ 5] = '4', [ 6] = '5', [ 7] = '6', [ 8] = '7', [ 9] = '8',[ 9] = '8', [10] = '9',
		
		[16] = 'Q', [17] = 'W', [18] = 'E', [19] = 'R', [20] = 'T', [21] = 'Y', [22] = 'U', [23] = 'I', [24] = 'O', [25] = 'P',
		
		[30] = 'A', [31] = 'S', [32] = 'D', [33] = 'F', [34] = 'G', [35] = 'H', [36] = 'J', [37] = 'K', [38] = 'L',
		
		[44] = 'Z', [45] = 'X', [46] = 'C', [47] = 'V', [48] = 'B', [49] = 'N', [50] = 'M'
	};
	char sendDate[256] = {"scannerStatus:"};
	char scanner_event[254] = "/dev/input/";
	int scanner_fd;
	int ret;
	int num = 0;
	char Data[100] = {0};
	//char *scanner_event = (char *)args;
	int select_scanner = (int )args;
		char *bar = "bar:";
char ret_scanner_date[100] = {0};
	struct input_event scannerEvent; 
	int i = 0;
	fd_set rdfds;
	struct timeval tv; //store timeout

	getEvent(select_scanner,scanner_event);

	scanner_fd = open(scanner_event, O_RDONLY|O_NOCTTY|O_NONBLOCK);
	if (scanner_fd < 0)
	{ 
	    sendDate[strlen(sendDate)] = NO_CONNECT;
	    perror("不能打开扫描仪!"); 
	    return;
	}
	sendDate[strlen(sendDate)] = MACHINE_FINE;
	sendDate[strlen(sendDate)] = '#';
	ret = write(fifo_wr, sendDate, strlen (sendDate));	/* 写管道 */	
	if(ret < 0)
	{
		printf("card send to QT  error:%s!\n",sendDate);
	}
	printf("DEV: scanner scanner%d is open!\n",select_scanner);

	while(1){

		tv.tv_sec = 0;
		tv.tv_usec = 20000;
		FD_ZERO(&rdfds); //clear rdfds
		FD_SET(scanner_fd, &rdfds); //add stdin handle into rdfds
				
		ret = select(scanner_fd + 1, &rdfds, NULL, NULL, &tv);
		if(ret < 0)
		perror("select\n");
		else if(ret == 0)
		{
			//超时，即无数据可读,且已经读取到有效的数据，开始上报数据			
			if(num> 0)
			{				
		
			//	printf("scanner bar:%s,%s\n",ret_date,Data );
				// 	ret_scanner_date[] = Keyboard_ascii[Data[i]];
				 	
				// 	//memset(ret_date,0,sizeof(ret_date));
				strcat(ret_scanner_date,bar);
				strcat(ret_scanner_date,Data);
				ret_scanner_date[strlen(ret_scanner_date)] = '#';
				printf( ret_scanner_date);
				 printf(" ....\n");
				// printf("scanner write date:%s\n",ret_scanner_date );
				 ret = write(fifo_wr, ret_scanner_date, strlen (ret_scanner_date));
				if(ret < 0)
				{
					printf("scanner write to fifo error!\n"); 
					exit(1);
				}	
				 memset(Data,0,sizeof(Data));
				 memset(ret_scanner_date,0,sizeof(ret_scanner_date));
				 num  = 0;
			}
	
		}
	//如果有数据读
		if(FD_ISSET(scanner_fd,&rdfds))
		{
			
			ret = read(scanner_fd,&scannerEvent,sizeof(scannerEvent));
			if( ret < 0){
				perror("can not read Scanner!\n"); 
			}
			if( scannerEvent.type==1 && scannerEvent.value==1 ){ 		
			Data[num] = Keyboard_ascii[scannerEvent.code];
			num++;
			}
		}

			
	}
	
	close(scanner_fd);
	
return;

}

